import { onBeforeUnmount } from "vue";
import { AppRequest } from "../wrap/request";
import { APIRequest as APIRequestTool } from "./tool";

import type { RequestDefaultConfig } from "../request.type";
import type { UseRequestResArr, UseRequestRes } from "./tool";
function useRequest() {
    const _reqMap: Map<string, AppRequest> = new Map();
    // 删除
    const _removeReq = (uuid: string) => {
        _reqMap.delete(uuid);
    };
    const _pushReq = (req: AppRequest) => {
        _reqMap.set(req.uuid, req);
    };

    onBeforeUnmount(() => {
        // 遍历
        _reqMap.forEach((v) => {
            v.cancel();
        });

        // 当cancel 时,  也会 导致请求 完成(但是 报错了), 也会 执行 _removeReq
        // 清空
        _reqMap.clear();
    });

    // 包装请求
    function APIRequest<
        T extends [RequestDefaultConfig, RequestDefaultConfig, ...RequestDefaultConfig[]]
    >(...args: T): UseRequestResArr;
    function APIRequest<T extends [] | [RequestDefaultConfig]>(...args: T): UseRequestRes;
    function APIRequest<T extends RequestDefaultConfig[]>(
        ...args: T
    ): UseRequestResArr | UseRequestRes {
        return APIRequestTool(
            args,
            function push(item: AppRequest) {
                _pushReq(item);
            },
            function remove(uuid: string) {
                _removeReq(uuid);
            }
        );
    }
    return {
        APIRequest,
    };
}

export { useRequest };
